package com.neouton.crm.generalPayRequest.service.impl;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.neouton.common.entity.ActivitiVO;
import com.neouton.common.util.*;
import com.neouton.crm.approval.entity.ApprovalVO;
import com.neouton.crm.approval.service.IApprovalService;
import com.neouton.crm.dictionary.entity.DictionaryLookupItemVO;
import com.neouton.crm.dictionary.service.IDictionaryService;
import com.neouton.crm.entity.NoticVo;
import com.neouton.crm.entity.SysUserEntity;
import com.neouton.crm.generalPayRequest.entity.GeneralPayRequest;
import com.neouton.crm.generalPayRequest.mapper.GeneralPayRequestMapper;
import com.neouton.crm.generalPayRequest.service.GeneralPayRequestService;
import com.neouton.crm.managerPayPlan.service.ManagerPaymentPlanService;

import com.neouton.crm.product.mapper.ProductInfoMapper;
import com.neouton.crm.supplier.entity.SupplierVO;
import com.neouton.crm.transpondEmail.mapper.TranspondEmailMapper;
import com.neouton.crm.transpondEmail.service.TranspondEmailService;
import com.neouton.feginClient.FeginMessageService;
import com.neouton.feginClient.FeginService;
import com.neouton.feginClient.WorkFlowFeginService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;

@Service
public class GeneralPayRequestServiceImpl  implements GeneralPayRequestService {

    @Resource
    private GeneralPayRequestMapper generalPayRequestMapper;

    @Resource
    private IDictionaryService dictionaryService;

    @Resource
    private IApprovalService approvalService;

    @Resource
    private FeginMessageService feginMessageService;

    @Resource
    private ProductInfoMapper productInfoMapper;
    @Resource
    private WorkFlowFeginService workFlowFeginService;

    @Resource
    private ManagerPaymentPlanService managerPaymentPlanService;

    @Resource
    FeginService feginService;

    @Value("${webSit.web}")
    private String webSitUrl;

    @Resource
    private TranspondEmailMapper transpondEmailMapper;

    @Resource
    private TranspondEmailService transpondEmailService;


    @Override
    public PageUtil<GeneralPayRequest> queryGeneralPayRequestList(IPage<GeneralPayRequest> page, GeneralPayRequest managerPayRequest, List<SysUserEntity> userList, String token) {
        if (managerPayRequest.getOrderByProp() != null) {
            managerPayRequest.setOrderByProp(StringUtils.camelToUnderline(managerPayRequest.getOrderByProp()));
        }
        IPage<GeneralPayRequest> iPage = generalPayRequestMapper.queryGeneralPayRequestList(page, managerPayRequest, userList);
        List<GeneralPayRequest> list  =  iPage.getRecords();
        if(!list.isEmpty()){
            BigDecimal paymentMoneyPage = new BigDecimal(0);
            BigDecimal eliminationMoneyPage = new BigDecimal(0);
            for (GeneralPayRequest  prvo: list) {
                //prvo.setPaymentTable(paymentRequestMapper.queryPaymentTablesByApprovalId(prvo.getApprovalId()));
                if(StringUtils.isNotEmpty(prvo.getPaymentMoney())){
                    paymentMoneyPage = paymentMoneyPage.add(new BigDecimal(prvo.getPaymentMoney()));
                }
                if(StringUtils.isNotEmpty(prvo.getEliminationMoney())) {
                    eliminationMoneyPage = eliminationMoneyPage.add(new BigDecimal(prvo.getEliminationMoney()));
                }
            }
            list.get(0).setPaymentMoneyPage(String.valueOf(paymentMoneyPage));
            list.get(0).setEliminationMoneyPage(String.valueOf(eliminationMoneyPage));
            iPage.setRecords(list);

        }
        return new PageUtil<>(iPage);
    }

    @Override
    public GeneralPayRequest saveGeneralPayRequest(GeneralPayRequest entity, String token) {
        //1.发起工作流
        //1）获取下一审批人，暂定总经理
        //获取审批人
        SysUserEntity user = dictionaryService.queryMenuUserIdsByCode("finance").get(0);
        //获取人员信息
        Integer businessId = this.startGeneralPayRequestApproval();
        //2.记录本地审批数据
        //生成审批主表信息，日志信息
        ApprovalVO approval = approvalService.initApprovalAndLog(businessId, 51, entity.getAskReason(), "",
                user.getUserId(),"");
        //之后更新/保存
        entity.setApprovalId(approval.getApprovalId());

        //判断是新增提交还是编辑提交
        if(entity.getPayRequestId()!= null){
            //根据采购单id判断是否存在中间表
                //修改收票记录数据
                GeneralPayRequest generalPayRequest = generalPayRequestMapper.queryGeneralPayRequestByID(entity.getPayRequestId());
                generalPayRequestMapper.backUpGeneralPayRequest(generalPayRequest.getPayRequestId(), AuthUtils.getUserId());
                generalPayRequestMapper.updateGeneralPayRequestById(entity);
        }else{
            //根据采购单id判断是否存在中间表
                entity.setPlanPeriod("1");
                generalPayRequestMapper.saveGeneralPayRequest(entity);


            //直接保存收票记录数据
        }
        //修改转发人
        if(!CollectionUtils.isEmpty(entity.getTranspondUsers())) {
            transpondEmailMapper.insertTranspondEmailInfoByUser(entity.getApprovalId(),entity.getTranspondUsers());
        }
        //数据保存完，发送审批邮件给审批人
        //调用通知接口生成待办通知
        if(AuthUtils.getUserAccount().equals(user.getAccount())){
            //跳过第一步审批
            this.approvedGeneralPayRequest(entity,token,true);
        }else {

            //调用通知接口生成待办通知
            Integer userId = AuthUtils.getUserId();
            CompletableFuture.runAsync(() -> this.pushNotic(approval.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                    userId, 0, 51, user.getUserId(), token));
        }

        return entity;
    }

    @Override
    public List<GeneralPayRequest> queryGeneralPayRequestMoney(GeneralPayRequest managerPayRequest) {
        List<GeneralPayRequest> managerPayRequests =  generalPayRequestMapper.queryGeneralPayRequestMoney(managerPayRequest);
        List<GeneralPayRequest> list = new ArrayList<>();
        if(managerPayRequests.size() > 0){
            managerPayRequests.get(0).setTranspondUsers(transpondEmailService.queryTranspondByApprovalId(managerPayRequest.getApprovalId()));
        }

        return managerPayRequests;
    }

    @Override
    public boolean rejectionGeneralPayRequest(GeneralPayRequest entity, String token) {
        ApprovalVO approval = approvalService.queryApprovalByAppID(entity.getApprovalId());
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setBusinessId(approval.getBusinessId());
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        workFlowFeginService.deleteInstance(activitiVO);
        //驳回
        SysUserEntity user = null;
        Integer workState;
        String titel;

        Integer todoUser;
        SysUserEntity askUser = feginService.searchUserInfoById(approval.getCreator(), token).getResult();
        user = askUser;
        workFlowFeginService.deleteInstance(activitiVO);

        //驳回至起点
        workState = 1;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        titel= "【系统通知】通用付款申请 - 流程单审批驳回通知";
        String msg = "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                    "<div><p style='text-indent: 2em'>您好，您有一张新的付款申请审批已被驳回：</p></div>"+
                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批人："+ AuthUtils.getUserName()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批意见："+ (StringUtils.isEmpty(entity.getAppReason()) ? "" : entity.getAppReason())+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批时间："+simpleDateFormat.format(new Date())+"</p></div>"+
                    "<div><p style='text-indent: 2em'>付款名称："+entity.getPayName()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>付款金额："+entity.getPaymentMoney()+"元</p></div>"+
                    "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 待办事项 - 待办审批 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";

        approvalService.approvalRejection(null,entity.getApprovalId());
        todoUser = 0;
        //记录日志
        approvalService.insertApprovalLog(approval.getApprovalId(),"驳回",
                "",entity.getAppReason());
        SysUserEntity finalUser = user;
        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(),null,titel,msg,token));
        Integer userId = AuthUtils.getUserId();
        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(entity.getApprovalId(),  approval.getCreateDataTime(),
                userId,workState,51,todoUser,token));
        return true;
    }

    @Override
    public boolean approvedGeneralPayRequest(GeneralPayRequest entity, String token, boolean auto) {
        ApprovalVO approval = approvalService.queryApprovalByAppID(entity.getApprovalId());
        ActivitiVO activitiVO = new ActivitiVO();//最终审批人
        activitiVO.setBusinessId(approval.getBusinessId());
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        ResponseAPI<ActivitiVO> processNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);

        SysUserEntity user= null ;
        Integer workState;
        String titel;
        String msg;
        Integer todoUser ;
        String ccUser = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SysUserEntity askUser = feginService.searchUserInfoById(approval.getCreator(),token).getResult();
        if(auto){
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "系统判定跳过",entity.getAppReason());
        }else {
            //记录日志
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "",entity.getAppReason());
        }
        if( "出纳审批".equals(processNodeNameAndCode.getResult().getName()) ){
            user=askUser;
            workState = 1;
            todoUser = 0;
            workFlowFeginService.approvalProcessByBusinessId(activitiVO);

            titel = "【系统通知】通用付款申请 - 流程单审批通过通知";
            ccUser = queryManagerPayRequestCC();

                msg="<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                        "<div><p style='text-indent: 2em'>您好，您付款申请审批已通过：</p></div>"+
                        "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>付款名称："+entity.getPayName()+"</p></div>"+
                        "<div><p style='text-indent: 2em'>付款金额："+entity.getPaymentMoney()+"元</p></div>"+
                        "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 待办事项 - 待办审批 " +
                        "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
                        "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                        "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";


            approvalService.approved(null,entity.getApprovalId());
            //记录日志
            String finalCcUser = ccUser;
            SysUserEntity finalUser = user;
            String bccEmail = transpondEmailService.selectTranspondEmailStr(entity.getApprovalId());
            CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(),finalCcUser +"," +bccEmail,titel,msg,token));
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(entity.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                    approval.getCreator(),workState,51,todoUser,token));
        } else {
            if("财务审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("chairman").get(0);
                activitiVO.getCustomParams().put("chairman",user.getAccount());
            } else if("董事长审批".equals(processNodeNameAndCode.getResult().getName())) {
                user = dictionaryService.queryMenuUserIdsByCode("cashier").get(0);
                activitiVO.getCustomParams().put("cashier",user.getAccount());
            }

            workFlowFeginService.approvalProcessCustomUserByBusinessId(activitiVO);
            ResponseAPI<ActivitiVO> nextProcessNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
            if(nextProcessNodeNameAndCode.getResult().getAssignee().equals(processNodeNameAndCode.getResult().getAssignee())){
                this.approvedGeneralPayRequest(entity,token,true);
            }else{
                workState = 0;
                todoUser = user.getUserId();

                approvalService.updateNextApproverByApprovalId(user.getUserId(),entity.getApprovalId());
                CompletableFuture.runAsync(() -> NoticUtils.pushNotic(entity.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                        approval.getCreator(),workState,51,todoUser,token));
            }

        }
        return true;
    }

    @Override
    public GeneralPayRequest queryGeneralPayRequestHistory(Integer approvalId) {
        GeneralPayRequest generalPayRequest = generalPayRequestMapper.queryGeneralPayRequestHistory(approvalId);
        if(generalPayRequest == null){
            GeneralPayRequest pRequestVo = new GeneralPayRequest();
            pRequestVo.setApprovalId(approvalId);
            generalPayRequest = this.queryGeneralPayRequestMoney(pRequestVo).get(0);
        }
        generalPayRequest.setTranspondUsers(transpondEmailService.queryTranspondByApprovalId(approvalId));
        return generalPayRequest;
    }



    @Override
    public List<GeneralPayRequest> queryPaymentRequestListInfo(GeneralPayRequest entity, List<SysUserEntity> userList, String token) {
        if (entity.getOrderByProp() != null) {
            entity.setOrderByProp(StringUtils.camelToUnderline(entity.getOrderByProp()));
        }
        List<GeneralPayRequest> list = generalPayRequestMapper.queryPaymentRequestListInfo(entity, userList);
        return list;
    }

    @Override
    public void exportPaymentRequestInfo(HttpServletResponse response, List<GeneralPayRequest> list, String token) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<String> statesList = new ArrayList<>();
        statesList.add("approvalStatus");
        statesList.add("linkfieId");
        JSONObject userObject = feginService.getUserInfo(token);
        JSONObject jsonObject = feginService.queryDictionaryLookupInfo("crm", statesList);
        List<String> classfiedCode = new ArrayList<>();
        classfiedCode.add("payMethod");
        classfiedCode.add("receiveInvoice");
        classfiedCode.add("payIsNot");
        classfiedCode.add("payPlanPeriodNum");
        Map<String, List<DictionaryLookupItemVO>> listMap = dictionaryService.queryDictionaryLookupInfo(1, classfiedCode);
        for (int i = 0; i < list.size(); i++) {
            GeneralPayRequest prVO = list.get(i);
            prVO.setPayRequestId(i+1);
            if(prVO.getSupplier()!= null){
                prVO.setSupplierName(selSupplierName(prVO.getSupplier().getSupplierId()));
            }
            String str = "";
            String [] planPeriods;
            if(prVO.getPlanPeriod()!= null&&prVO.getPlanPeriod().indexOf(",")>0){
                planPeriods = prVO.getPlanPeriod().split(",");
                for ( int j =0 ;j<planPeriods.length ;j ++) {
                    if(j==planPeriods.length -1){
                        str += getCRMDictionaryNameByCode("payPlanPeriodNum",listMap).get(planPeriods[j] )+"";
                    }else{
                        str += getCRMDictionaryNameByCode("payPlanPeriodNum",listMap).get(planPeriods[j] )+",";
                    }

                }
                prVO.setPlanPeriodName(str);
            }else{
                prVO.setPlanPeriodName((String)getCRMDictionaryNameByCode("payPlanPeriodNum",listMap).get(prVO.getPlanPeriod() + ""));
            }
            prVO.setHeadName((String)getUserNameById(userObject).get(prVO.getHead().getUserId()));
            prVO.setOwnerName((String)getUserNameById(userObject).get(prVO.getOwner().getUserId()));
            prVO.setPayMethodName((String) getCRMDictionaryNameByCode("payMethod", listMap).get(prVO.getPayMethod() + ""));
            prVO.setReceiveInvoiceName((String) getCRMDictionaryNameByCode("receiveInvoice", listMap).get(prVO.getReceiveInvoice() + ""));
            prVO.setApprovalStatusName((String)getDictionaryNameByCode("approvalStatus",jsonObject).get(prVO.getApproval().getApprovalStatus() + ""));
            prVO.setPayIsNotName((String) getCRMDictionaryNameByCode("payIsNot", listMap).get(prVO.getPayIsNot() + ""));
            prVO.setPrIsNotName((String)getDictionaryNameByCode("linkfieId",jsonObject).get(prVO.getPrIsNot() + ""));
            prVO.setMoneyDateTime(dateFormat.format(prVO.getMoneyDate()));
        }
        //获取yml模板位置
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        String path = "application.yml";
        factoryBean.setResources(new ClassPathResource(path));
        Properties properties = factoryBean.getObject();
        String templatePath = String.valueOf(properties.get("report.generalPayRequestTemplate"));
        //依据根目录获取模板位置
        TemplateExportParams params = new TemplateExportParams(templatePath);
        Map<String, Object> map = new HashMap<>();
        map.put("paymentRequestInfo",list);
        ReportUtils.exportExcel(params,map,"通用付款申请信息",response);
    }

    @Override
    public PageUtil<GeneralPayRequest> queryGeneralPayRequestApprovalList(IPage<GeneralPayRequest> page, GeneralPayRequest managerPayRequest, String token) {
        if (managerPayRequest.getOrderByProp() != null) {
            managerPayRequest.setOrderByProp(StringUtils.camelToUnderline(managerPayRequest.getOrderByProp()));
        }
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(51);
        List<ApprovalVO> appList = new ArrayList<>();
        if ("todo".equals(managerPayRequest.getParamType())) {
            appList = approvalService.queryApprovalByPage(approvalVO);
        } else if ("done".equals(managerPayRequest.getParamType())) {
            appList = approvalService.queryApprovalDoneRecordByType(approvalVO);
        } else {
            appList = approvalService.queryApprovalRecordByType(approvalVO, token);
        }
        if (appList == null || appList.isEmpty()) {
            return new PageUtil(new PageDTO());
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item : appList) {
                arrayList.add(item.getApprovalId());
            }
            if (arrayList.size() > 0) {
                managerPayRequest.setApprovalIds(arrayList);
            } else {
                arrayList.add(0);
                managerPayRequest.setApprovalIds(arrayList);
            }
            IPage<GeneralPayRequest> iPage = generalPayRequestMapper.queryGeneralPayRequestList(page, managerPayRequest, null);
            List<GeneralPayRequest> list = iPage.getRecords();
            if (!list.isEmpty()) {
                BigDecimal paymentMoneyPage = new BigDecimal(0);
                BigDecimal eliminationMoneyPage = new BigDecimal(0);
                for (GeneralPayRequest prvo : list) {
                    //prvo.setPaymentTable(paymentRequestMapper.queryPaymentTablesByApprovalId(prvo.getApprovalId()));
                    if (StringUtils.isNotEmpty(prvo.getPaymentMoney())) {
                        paymentMoneyPage = paymentMoneyPage.add(new BigDecimal(prvo.getPaymentMoney()));
                    }
                    if (StringUtils.isNotEmpty(prvo.getEliminationMoney())) {
                        eliminationMoneyPage = eliminationMoneyPage.add(new BigDecimal(prvo.getEliminationMoney()));
                    }
                }
                list.get(0).setPaymentMoneyPage(String.valueOf(paymentMoneyPage));
                list.get(0).setEliminationMoneyPage(String.valueOf(eliminationMoneyPage));
                iPage.setRecords(list);

            }
            return new PageUtil<>(iPage);
        }
    }

    @Override
    public Boolean deletePayedRequestById(Integer payRequestId) {
        return generalPayRequestMapper.deletePayedRequestById(payRequestId);
    }

    @Override
    public void updatePrIsNotById(Integer payRequestId) {
        generalPayRequestMapper.updatePrIsNotById(payRequestId,"2");
    }


    /**
     * 开启审批流程
     * @param
     * @param user
     * @return
     */
    private Integer startGeneralPayRequestApproval(){
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        activitiVO.setProcessName("通用付款申请");
        activitiVO.setProcessCode("general_pay_request_approval");
        activitiVO.setNextNodeParams("finance");
        //行政专员
        SysUserEntity business = dictionaryService.queryMenuUserIdsByCode("finance").get(0);
        activitiVO.setNextNodeAssignee(business.getAccount());
        ResponseAPI<ActivitiVO> responseAPI = workFlowFeginService.startMaxVersionProcessByDesignCodeCustomParams(activitiVO);
        return responseAPI.getResult().getBusinessId();
    }


    private void pushNotic(Integer workflowId, Timestamp askTime,Integer askUserId,
                           Integer workState,Integer taskType,Integer todoUserId,String token){
        NoticVo vo = new NoticVo();
        vo.setFromSystem("crm");
        vo.setWorkflowId(workflowId);
        vo.setAskUserId(askUserId);
        vo.setAskTime(askTime);
        vo.setWorkState(workState);
        vo.setTaskType(taskType);
        vo.setTodoUserId(todoUserId);
        feginMessageService.pushNoticToDB(token,vo);
    }


    /**
     * 获取综管收票记录抄送人
     * @return
     */
    private String queryManagerPayRequestCC(){
        //获取抄送人
        List<SysUserEntity> userIds = dictionaryService.queryCcUserIdsByCode("generalPayRequestCC");
        StringBuilder emailList = new StringBuilder();
        for (int i = 0; i < userIds.size(); i++) {
            if (userIds.size()-1 == i){
                emailList.append(userIds.get(i).getEmail());
            }else {
                emailList.append(userIds.get(i).getEmail());
                emailList.append(",");
            }
        }
        return emailList.toString();
    }

    private String selSupplierName(Integer supplierId) {
        List<SupplierVO> list = productInfoMapper.querySuppliers();
        if (!CollectionUtils.isEmpty(list)) {
            for (SupplierVO item : list) {
                if (item.getSupplierId().equals(supplierId)) {
                    return item.getSupplierName();
                }
            }
            return null;
        }
        return null;
    }

    private Map getCRMDictionaryNameByCode(String itemCode, Map listMap) {
//        LinkedHashMap linkedHashMap = (LinkedHashMap) listMap.get("result");
        List<DictionaryLookupItemVO> dataDictionaryArray = (List) listMap.get(itemCode);
        Map<String, String> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(dataDictionaryArray)) {
            for (DictionaryLookupItemVO item : dataDictionaryArray) {
                map.put(item.getItemCode(), item.getItemName());
            }
            return map;
        }
        return null;
    }

    private Map getDictionaryNameByCode(String itemCode, JSONObject jsonObject) {
        LinkedHashMap linkedHashMap = (LinkedHashMap) jsonObject.get("result");
        List<Map> dataDictionaryArray = (List) linkedHashMap.get(itemCode);
        Map<String, String> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(dataDictionaryArray)) {
            for (Map item : dataDictionaryArray) {
                map.put(item.get("itemCode").toString(), item.get("itemName").toString());
            }
            return map;
        }
        return null;
    }

    private Map getUserNameById(JSONObject jsonObject) {
        List<Map> dataDictionaryArray = (List) jsonObject.get("result");
        Map<Integer, String> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(dataDictionaryArray)) {
            for (Map item : dataDictionaryArray) {
                map.put((Integer) item.get("userId"), (String) item.get("loginName"));
            }
            return map;
        }
        return null;
    }
}
